<?php


namespace app\common\model;

use app\admin\model\test\hld\Cate as hldCate;
use app\admin\model\test\mbti\Cate as mbtiCate;
use app\admin\model\test\zym\Cate as zymCate;
use PhpOffice\PhpWord\Shared\Converter;
use think\Model;
use PhpOffice\PhpWord\PhpWord;
use app\common\model\TestDyznAnswer;
use app\common\model\TestHldAnswer;
use app\common\model\TestMbtiAnswer;
use app\common\model\TestZymAnswer;
use app\admin\model\test\dyzn\Cate as dyznCate;
// use app\admin\model\User;

class Download extends Model
{
    const PARAGRAPH_STYLE_NAME = 'pStyle';  //段落样式
    const FONT_STYLE_NAME      = 'rStyle';  //字体样式
    protected $phpWord;
    protected $user;
    protected $titleStyle;
    public function __construct($data = [])
    {
        parent::__construct($data);
        $this-> phpWord = new PhpWord();
        $this-> user    = new User();

        $this-> phpWord-> addParagraphStyle( self::FONT_STYLE_NAME, [//设置段落样式
            'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::START,              //居中校准
            'spaceAfter'  => 300,                                                   //标题后部预留长度
            'spaceBefore' => 500,                                                    //标题前部预留长度
            'name'      => '微软雅黑',
            'size'      => 30,
            'bold'      => true,
        ] );

        $this -> titleStyle = [//设置段落样式
            'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::START,              //居中校准
            'spaceAfter'  => 300,                                                   //标题后部预留长度
            'spaceBefore' => 500,                                                    //标题前部预留长度
            'name'      => '微软雅黑',
            'size'      => 16,
            'bold'      => true
        ];
    }

    /**
     * 模型实例化方法
     * 传参实例化不同模型，例如：
     * $dyzncs实例化多元化智能测试模型等等
     * 当标识不为false时，则不会实例化对应模型
     */
    public function instantiate( $hldcs = false, $mbtics = false, $dyzncs = false, $zymcs = false)
    {
        $array = [
            'hldcs'     => '',      //霍兰德测试模型存放
            'mbtics'    => '',      //MBTI测试模型存放
            'dyzncs'    => '',      //多元化智能测试模型存放
            'zymcs'     => ''      //职业锚测试模型存放
        ];
        /**
         * 判断传参规则，需要实例化哪些模型
         */
        if( $hldcs != false )      //霍兰德测试
            $array[ 'hldcs' ]   = new TestHldAnswer();
        if( $mbtics != false )     //MBTI测试
            $array[ 'mbtics' ]   = new TestMbtiAnswer();
        if ( $dyzncs != false )    //多元化智能测试
            $array[ 'dyzncs' ]   = new TestDyznAnswer();
        if( $zymcs != false )      //职业锚测试
            $array[ 'zymcs' ]    = new TestZymAnswer();
        return $array;              //返回实例化数组
    }

    /**
     * 获取用户信息
     * 传参：user_id：用户唯一标识
     */
    public function getUserInfo( $userId )
    {
        $userInfo = $this-> user-> where( 'id',$userId )-> find(); //获取用户信息
        return $userInfo;
    }

    /**
     * 获取用户测试数据
     * 根据传递数组的不同，自主选择获取哪个表中的数据
     * 传参:$user_id为用户唯一标识
     * $array为实例化模型组
     */
    public function getRows( $userId,$array = [] )
    {
        $rows = [];
        if( $array['hldcs'] != '' )         //获取霍兰德测试数据判断
            $rows[ 'hldcs' ]  = $array[ 'hldcs' ]->  where( 'user_id', $userId )-> find();  
        if( $array['mbtics'] != '' )        //获取MBTI测试数据判断
            $rows[ 'mbtics' ] = $array[ 'mbtics' ]-> where( 'user_id', $userId )-> find();
        if( $array['dyzncs'] != '' )        //获取多元化智能测试数据判断
            $rows[ 'dyzncs' ] = $array[ 'dyzncs' ]-> where( 'user_id', $userId )-> find();
        if( $array['zymcs'] != '' )         //获取职业锚测试数据判断
            $rows[ 'zymcs' ]  = $array[ 'zymcs' ]->  where( 'user_id', $userId )-> find();
        return $rows;
    }

    /**
     * 生成报表公共方法
     * 传参：$array:标识数组
     */
    public function GenerateHead( $data,$userInfo )
    {
        $section = $this-> phpWord-> addSection();                                  //创建空白页面

        $sectionStyle = array('orientation' => null,
//            'marginLeft' => 1800,
//            'marginRight' => 1800,
            'marginTop' => 1800,
            'marginBottom' => 900,
            'lineHeight'=>2,
            // 'pageNumberingStart'=>1 //页码是从1开始
            );
        $section-> setStyle($sectionStyle);


        // $imgUrl = $_SERVER['DOCUMENT_ROOT'].'/assets/img/1.jpg';            //获取思达LOGO——URL地址
        // $section-> addImage( $imgUrl, [                                             //添加封面图片
        //    'width'         => 500,                                                 //设置封面宽度
        //    'marginLeft'     => 5,
        //    'height'        => 400,                                                  //设置封面高度
        //    'align'         => \PhpOffice\PhpWord\SimpleType\Jc::START,            //设置对对齐方式
        //    'marginTop'        => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(-3),
        // ]);

        $this-> phpWord-> addParagraphStyle( self::PARAGRAPH_STYLE_NAME, [//设置段落样式
            'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
            'spaceAfter'  => 300,                                                   //标题后部预留长度
            'spaceBefore' => 300,                                                    //标题前部预留长度
            'lineHeight'  => 2,  // 行间距
        ] );

        $userInfoStyle = 'userinfo';
        $this-> phpWord-> addParagraphStyle( $userInfoStyle, [//设置段落样式
            'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::START,              //居中校准
            'spaceAfter'  => 300,                                                   //标题后部预留长度
            'spaceBefore' => 500,                                                    //标题前部预留长度
            'lineHeight'  => 2,  // 行间距
        ] );

        


        $blankSpace = '               ';
        $section-> addText('测评报告',
            [
                'size'    => 36,
                'bold' => true,
                'name'=>'黑体',
                'color'=>'#1482ac'
            ], [
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
                'spaceAfter'  => 300,                                                   //标题后部预留长度
                'spaceBefore' => 4500,                                                    //标题前部预留长度
            ]
        );     //添加标题文本

        $name   = "姓名：".$userInfo-> nickname.'    ';                              //用户姓名
        $section -> addText( $blankSpace.$name,[ 'size' => 16 ,'name' => '黑体'], [
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::LEFT,              //居中校准
                'spaceAfter'  => 350,
                'spaceBefore' => 100,
            ],$userInfoStyle );//添加用户姓名
        if( $userInfo-> gender == 1 )                                               //用户性别判断
            $gender = '男';
        else
            $gender = '女';
        $gender  = "性别：".$gender.'    ';
        $section -> addText( $blankSpace.$gender,[ 'size'   => 16,'name' => '黑体'], [
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::LEFT,              //居中校准
                'spaceAfter'  => 350,                                                   //标题后部预留长度
                'spaceBefore' => 100,                                                    //标题前部预留长度
            ],$userInfoStyle );//添加用户性别

        switch ( $data )                                                            //获取时间：通过判断获取用户已做过测试中的测试时间
        {
            case ( !empty($data['hldcs'])  && $data['hldcs']-> create_time != '' ):  
                $time =$data['hldcs']->create_time ? $data['hldcs']->create_time : '' ;
                break;
            case ( !empty($data['mbtics']) && $data['mbtics']-> create_time != '' ):  //MBTI测试时间获取
                $time = $data['mbtics']->create_time ? $data['mbtics']->create_time : '' ;
                break;
            case ( !empty($data['dyzncs'])  && $data[ 'dyzncs' ]-> create_time != '' ):  //多元化智能测试时间获取
                $time = $data[ 'dyzncs' ]->create_time ? $data['dyzncs']->create_time : '' ;
                break;
            default:  //职业锚测试时间获取
                $time = $data['zymcs']->create_time ? $data['zymcs']->create_time : '' ;
                break;
        }
        $time  = '测评时间：'.date( 'Y-m-d', $time );
        $this-> phpWord-> addParagraphStyle(self::PARAGRAPH_STYLE_NAME, [
            'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,
            'spaceAfter' => 350,'spaceBefore' => 100,

        ]);

        $section -> addText( $blankSpace.$time,[ 'size' => 16,'name' => '黑体'], [
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::LEFT,              //居中校准
                'spaceAfter'  => 350,                                                   //标题后部预留长度
                'spaceBefore' => 100,                                                    //标题前部预留长度
            ],$userInfoStyle );//添加用户信息


        // $imgUrl = ROOT_PATH.'public/assets/img/bgtop.png'; //获取封面URL地址
        // $logoUrl = ROOT_PATH.'public/assets/img/header.png';
        // $botImgUrl = ROOT_PATH.'public/assets/img/bgbottom.png';

        // $section->addImage(
        //     // $imgUrl,
        //     array(
        //         'width'            => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(9),
        //         'height'           => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(7.5),
        //         'positioning'      => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
        //         'posHorizontal'    => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_LEFT,
        //         'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE,
        //         'posVerticalRel'   => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE,
        //         'marginLeft'       => '-3',
        //         'marginTop'        => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(-3),
        //     )
        // );

        // $section->addImage(
        //     // $logoUrl,
        //     array(
        //         'width'            => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(5.5),
        //         'height'           => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(3.6),
        //         'positioning'      => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE,
        //         'posHorizontal'    => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_RIGHT,
        //         'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE,
        //         'posVerticalRel'   => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE,
        //         // 'marginRight'       => '5',
        //         // 'marginTop'        => '300',
        //     )
        // );
        // $section->addImage(
        //     // $botImgUrl,
        //     array(
        //         'width'            => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(9),
        //         'height'           => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(7.5),
        //         'positioning'      => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
        //         'posHorizontal'    => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_RIGHT,
        //         'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE,
        //         'posVerticalRel'   => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE,
        //         'marginLeft'       => '-3',
        //         'marginTop'        => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(-3),
        //         'posVertical'      => \PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_BOTTOM,
        //     )
        // );
        $section2 = $this-> phpWord-> addSection();                                  //创建空白页面
        // $logoUrl = ROOT_PATH.'public/assets/img/replaceLogo.png';         //获取思达LOGO——URL地址
        // $header= $section->createHeader();
        // $header->addImage($logoUrl,['width'=> 180,'height'=>30,'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::LEFT]);
        // $header->addPreserveText('                                      思行天下   无远不达',['size'=>16,'name'=>'华文行楷','bold' => true,],['alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,'spaceAfter'  => 10,'marginTop'=>5]);
        $footer = $section2->createFooter();
        // $footer->addImage($logoUrl,['width'=> 100,'height'=>30,'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::LEFT]);
        $footer->addPreserveText('……………………………………………………………………………………………………{PAGE}',['size'=>12,'name'=>'黑体'],['alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::RIGHT,'marginBottom'  => 10]);
        $section2-> addText('目录',
            [
                'size'    => 18,
                'name'=>'宋体',
            ], [
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
                'spaceAfter'  => 300,                                                   //标题后部预留长度
                'spaceBefore' => 450,                                                    //标题前部预留长度
            ]
        );     //添加标题文本


        // 封面后边添加——目录
        // $dir .= '报告导语  ……………………………………………………………………1<br/>';
        // $dir .= '阅读建议  ……………………………………………………………………2<br/>';
        // $dir .= '霍兰德职业兴趣测评  ………………………………………………………3<br/>';
        // $dir .= 'MBTI性格测评 ………………………………………………………………4<br/>';
        // $dir .= '多元智能测评  ………………………………………………………………5<br/>';
        // $dir .= '职业锚测评……………………………………………………………………6<br/>';
        // $dir .= '报告总结………………………………………………………………………7<br/>';
        // $dir .= '人才发展建议…………………………………………………………………8<br/>';
        // $section2 -> addText($dir,[ 'size' => 14,'name' => '仿宋','lineHeight'  => 2]);//添加固定描述
        
        $section2 -> addText('报告导语  ……………………………………………………………………1',[ 'size' => 14,'name' => '仿宋','lineHeight'  => 2]);//添加固定描述
        $section2 -> addText('阅读建议  ……………………………………………………………………2',[ 'size' => 14,'name' => '仿宋','lineHeight'  => 2]);//添加固定描述
        $section2 -> addText('霍兰德职业兴趣测评  ………………………………………………………3',[ 'size' => 14,'name' => '仿宋','lineHeight'  => 2]);//添加固定描述
        $section2 -> addText('MBTI性格测评 ………………………………………………………………4',[ 'size' => 14,'name' => '仿宋','lineHeight'  => 2]);//添加固定描述
        $section2 -> addText('多元智能测评  ………………………………………………………………5',[ 'size' => 14,'name' => '仿宋','lineHeight'  => 2]);//添加固定描述
        $section2 -> addText('职业锚测评……………………………………………………………………6',[ 'size' => 14,'name' => '仿宋','lineHeight'  => 2]);//添加固定描述
        $section2 -> addText('报告总结………………………………………………………………………7',[ 'size' => 14,'name' => '仿宋','lineHeight'  => 2]);//添加固定描述
        $section2 -> addText('人才发展建议…………………………………………………………………8',[ 'size' => 14,'name' => '仿宋','lineHeight'  => 2]);//添加固定描述
        $section2->  addPageBreak();                                                 //设置分页符



        $section2-> addText('报告导语',
            [
                'size'    => 18,
                'name'=>'黑体',
            ], [
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::LEFT,              //居中校准
                //'spaceAfter'  => 300,                                                   //标题后部预留长度
                //'spaceBefore' => 450,                                                    //标题前部预留长度
            ]
        );     //添加标题文本
        $section2->addText('__________________________________________________________________________________________',['name'=>'黑体'],['spaceAfter'  => 300,'spaceBefore' =>2,'alignment'=> \PhpOffice\PhpWord\SimpleType\Jc::CENTER]);

        $Space = '      ';
        $Style = $Space.'职业生涯规划测评系统是通过一系列科学的手段和方法对人的基本素质及其绩效进行测量和评定的活动，并将其应用在人才发展与人才管理等企业管理领域。人才测评的作用在于引导你认识自身的个性特质、现有和潜在的优势以及帮助你重新认识自身的价值并使其持续增值;同时引导你对自己的综合优势与劣势进行对比分析，确立明确的职业发展目标与职业理想，评估出个人目标与现状间的距离。在更清楚的了解自己的前瞻与实际相结合的职业定位后,才能进一步搜索或发展新的或有潜力的职业机会。对比人才测评结果，能使你学会如何运用科学的方法,采取切实可行的步骤和措施，不断增强你的职业竞争力,实现自己的职业目标与理想。“尺有所短，寸有所长”，每个人都有不同于其他人的优势所在。变革所带来的紧迫感，要求个人必须不断提高素质，才能应对竞争的挑战，适应组织的发展要求和工作质量的要求。其次，企业更欢迎有准备的人才。通过本次人才测评能发挥个人的专长，开发自己的潜能，克服生涯发展困阻，避免人生陷阱，不断修正前进的方向，最后获得事业以及人生的成功。';
        // 报告导语
        $section2 -> addText($Style,[ 'size' => 14,'name' => '仿宋','lineHeight'  => 2]);//添加固定描述
        $section2->  addPageBreak();                                                 //设置分页符

        $section2-> addText('阅读建议',
            [
                'size'    => 18,
                'name'=>'黑体',
            ], [
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::LEFT,              //居中校准
                // 'spaceAfter'  => 300,                                                   //标题后部预留长度
                // 'spaceBefore' => 450,                                                    //标题前部预留长度
            ]
        );     //添加标题文本
       
        $section2->addText('__________________________________________________________________________________________',['name'=>'黑体'],['spaceAfter'  => 300,'spaceBefore' =>2,'alignment'=> \PhpOffice\PhpWord\SimpleType\Jc::CENTER]);

        // 阅读建议
        $section2 -> addText("在阅读本报告前，请您了解一下原则：",['size'=>14,'name' => '仿宋','lineHeight'  => 2]);
        $section2 -> addText("1.测评结果的准确性和可靠性依赖于被评价者在测验中态度是否认真、能否如实作答，是否答完题目以及答题所用时间是否在合理范围内等信息。",['size'=>14,'name' => '仿宋','lineHeight'  => 2]);
        $section2 -> addText("2.人才测评是基于受测者的能力、个性和兴趣等指标进行测量的，没有对受测者的专业知识、经验进行评估，请以科学的态度看待测评结果。",['size'=>14,'name' => '仿宋','lineHeight'  => 2]);
        $section2 -> addText("3.测评结果没有“好”与“差”之分，每种类型、特质均有其对应的优劣势，但相对于具体工作、岗位有“合适”与“不合适”的区别。",['size'=>14,'name' => '仿宋','lineHeight'  => 2]);
        $section2 -> addText("4.若您是初次阅读此类报告，最好是在专业人士的指导下阅读，或请专业人士为您进行解释。",['size'=>14,'name' => '仿宋','lineHeight'  => 2]);

        return $section2;
    }


    private function setheader($phpWord,$section){
        $fancyTableStyleName = 'Fancy Table';
        $fancyTableStyle = array(
            'borderBottomSize' => 30,
            'borderBottomColor' => '622423',
            'borderTopSize' => 6,
            'borderTopColor' => 'ffffff',
            'borderLeftSize' => 6,
            'borderLeftColor' => 'ffffff',
            'borderRightSize' => 6,
            'borderRightColor' => 'ffffff',
            'cellMargin' => 80,
            'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER,
            'cellSpacing' => 1);
        $fancyTableFirstRowStyle = array(
            'borderBottomSize' => 30,
            'borderBottomColor' => '000000',
            'bgColor' => 'ffffff');
        $fancyTableCellStyle = array(
            'borderBottomSize' => 6,
            'borderBottomColor' => '622423',
            'borderTopSize' => 6,
            'borderTopColor' => 'ffffff',
            'borderLeftSize' => 6,
            'borderLeftColor' => 'ffffff',
            'borderRightSize' => 6,
            'borderRightColor' => 'ffffff',
            'valign' => 'bottom',
            'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::END,'cellSpacing' => 20);
        $fancyTableFontStyle = array('size' => 20,'name'=>'华文行楷');
        $phpWord->addTableStyle($fancyTableStyleName, $fancyTableStyle, $fancyTableFirstRowStyle);


//        $section = $phpWord->addSection();

// Add first page header
        $header = $section->addHeader();
//        $header->firstPage();
        $table = $header->addTable($fancyTableStyleName);
        $table->addRow();
        $table->addCell(5000,$fancyTableCellStyle)->addImage('header.png', array('width' => 120, 'height' => 60));
        $cell = $table->addCell(4000,$fancyTableCellStyle);
        $textrun = $cell->addTextRun();
        $textrun->addText('思行天下   无远不达',$fancyTableFontStyle);
        $section -> addTextBreak();

    }

    /**
     * 组成文档中部测试信息（通过判断验证添加信息）
     */
    public function GenerateMiddle( $file, $data )
    {      
        if( $data[ 'hldcs' ]   != '' )      //判断生成霍兰德测试文本
            $file = $this-> GenerateHldcsTxt( $file, $data[ 'hldcs' ] );
        if( $data[ 'mbtics' ]  != '' )      //判断生成MBTI测试文本
            $file = $this-> GenerateMbticsTxt( $file, $data[ 'mbtics' ] );
        if( $data[ 'dyzncs' ] != '' )      //判断生成多元化智能测试文本
            $file = $this-> GenerateDyhzncsTxt( $file, $data[ 'dyzncs' ] );
        if( $data[ 'zymcs' ]   != '' )      //判断生成职业锚测试文本
            $file = $this-> GenerateZymcsTxt( $file, $data[ 'zymcs' ] );
        return $file;
    }

    // 报告总结
    public function GenerateReport( $file, $data )
    {
        if( $data[ 'mbtics' ]  != '' )      //判断生成MBTI测试文本
            $file = $this-> GenerateMbticsReport( $file, $data[ 'mbtics' ] );
        return $file;
    }

    // 人才建议
    public function GenerateAdvise( $file, $data )
    {
        if( $data[ 'mbtics' ]  != '' )      //判断生成MBTI测试文本
            $file = $this-> GenerateMbticsAdvise( $file, $data[ 'mbtics' ] );
        return $file;
    }
    /**
     * 组装多元化智能测试文本（当前只适用于本类）
     */
    private function GenerateDyhzncsTxt( $section,$data )
    {

        $cates = dyznCate::all();
        $row = TestDyznAnswer::get( $data-> id );

        $answers_ana = unserialize($row->answers_ana);
        $assData = [
            'cates' => $cates,
            'answers_ana'   => $answers_ana
        ];

        if( $data-> imgs )
            $img = unserialize( $data-> imgs );
        if( isset($img) )
        {
            $imgcount = count( $img );
            foreach ( $img as $ig )
            {
                $imgpath = $_SERVER['DOCUMENT_ROOT'].$ig;
                if(!is_file($imgpath)) continue;
                $info    = getimagesize($imgpath);
                $oheight = $height = $info[1];
                $owidth  = $width = $info[0];
                if( $imgcount == 1 )
                {
                    $width  = min($width,430);
                    $height = intval($oheight * ($width/$owidth));
                }
                $section-> addImage($_SERVER['DOCUMENT_ROOT'].$ig, array('width'=>450, 'height'=>400));
            }
        }

        // $section -> addText('多元智能测试得分',['name'=>'黑体','size'=>14,'bold' => true,'lineHeight'  => 2],$this -> titleStyle, self::PARAGRAPH_STYLE_NAME);
        // $section -> addText('职业锚测试得分',['name'=>'仿宋','size'=>14,'lineHeight'  => 2],self::FONT_STYLE_NAME, self::PARAGRAPH_STYLE_NAME);
        $str1 = ['成绩'];
        $str2 = ['得分'];
        $ana = [];
        $strong = '';
        $nomal = '';
        $weak = '';
        foreach($assData['cates'] as $k => $v){
            $str1[] = $v['name'];
            $str2[] = $assData['answers_ana'][$v['id']];
            $ana[$v['id']] = [
                'name'  => $v['name'],
                'score' => $assData['answers_ana'][$v['id']]
            ];
            if($assData['answers_ana'][$v['id']] > 16){
                $strong .= $v['name'].',';
            }elseif($assData['answers_ana'][$v['id']] > 8 && $assData['answers_ana'][$v['id']] <=16){
                $nomal .= $v['name'].',';
            }else{
                $weak .= $v['name'].',';
            }
        }
        $strong = trim($strong,',');
        $nomal = trim($nomal,',');
        $weak = trim($weak,',');


        $section->addTextBreak(1);
        $fancyTableStyleName = 'Fancy Table';
        $fancyTableStyle = array('borderSize' => 1, 'borderColor' => '006699', 'cellMargin' => 80, 'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER, 'cellSpacing' => 0);
        $fancyTableFirstRowStyle = array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF');
        $fancyTableCellStyle = array('valign' => 'center');
        $fancyTableFontStyle = array('bold' => true);
        $this-> phpWord-> addTableStyle($fancyTableStyleName, $fancyTableStyle, $fancyTableFirstRowStyle);
        $table = $section->addTable($fancyTableStyleName);


        // for ($r = 1; $r <= 2; $r++) {
        //     $table->addRow();
        //     if($r == 1){
        //         foreach ($str1 as $v){
        //             $table->addCell(1050, $fancyTableCellStyle)->addText($v, $fancyTableFontStyle);
        //         }
        //     }
        //     if($r == 2){
        //         foreach ($str2 as $v){
        //             $table->addCell(1050)->addText($v);
        //         }
        //     }
        // }

        $desc = "在表格中，得分越高说明你的这项能力越优势，反之，得分越低说明你的这项能力越不足。从图中可以看出：相比而言，你的";
        if($strong){
            $desc .= "最优能力分别是：$strong ;";
        }
        if($nomal){
            $desc .= "中等能力分别是：$nomal ;";
        }
        if($weak){
            $desc .= "弱项能力分别是：$weak ;";
        }

        $this-> phpWord-> addParagraphStyle( self::PARAGRAPH_STYLE_NAME, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::LEFT,'spaceAfter' => 300,'spaceBefore' => 500));
        $section -> addText($desc,['name'=>'仿宋','size'=>14,'lineHeight'  => 2],'', self::PARAGRAPH_STYLE_NAME,['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);
        return $section;
    }

    /**
     * 组装职业锚测试文本（当前只适用于本类）
     */
    private function GenerateZymcsTxt( $section, $data )
    {
        $cates = zymCate::all();
        $row = TestZymAnswer::get( $data-> id );

        if(!$row){
            $this -> redirect('zymtest');
        }
        $answers_ana = unserialize($row->answers_ana);
        $assData = [
            'cates' => $cates,
            'answers_ana'   => $answers_ana
        ];
        if($row -> imgs)
            $img = unserialize($row -> imgs);

        $languageEnGb = new \PhpOffice\PhpWord\Style\Language(\PhpOffice\PhpWord\Style\Language::ZH_CN);

        $this-> phpWord-> getSettings()-> setThemeFontLang($languageEnGb);

        $section = $this-> phpWord-> addSection();
        $this-> phpWord->addParagraphStyle(self::PARAGRAPH_STYLE_NAME, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,'spaceAfter' => 300,'spaceBefore' => 500));
        $section -> addText('职业锚测评',$this -> titleStyle, self::PARAGRAPH_STYLE_NAME);



        if(isset($img)){
            $imgcount = count($img);
            foreach ($img as $ig){
                $imgpath = $_SERVER['DOCUMENT_ROOT'].$ig;
                if(!is_file($imgpath)) continue;
                $info = getimagesize($imgpath);
                $oheight = $height = $info[1];
                $owidth = $width = $info[0];
                if($imgcount == 1)
                {
                    $width = min($width,430);
                    $height = intval($oheight * ($width/$owidth));
                }
                $section->addImage($_SERVER['DOCUMENT_ROOT'].$ig, array('width'=>$width, 'height'=>400));
            }
        }
        // $section -> addText('职业锚测试得分',['name'=>'仿宋','size'=>14,'bold' => true,'lineHeight'  => 2],self::FONT_STYLE_NAME, self::PARAGRAPH_STYLE_NAME);


        $str1 = ['成绩'];
        $str2 = ['得分'];
        $ana = [];
        $strong = '';
        $nomal = '';
        $weak = '';
        foreach($assData['cates'] as $k => $v){
            $str1[] = $v['name'];
            $str2[] = $assData['answers_ana'][$v['id']];
            $ana[$v['id']] = [
                'name'  => $v['name'],
                'score' => $assData['answers_ana'][$v['id']]
            ];
            if($assData['answers_ana'][$v['id']] > 16){
                $strong .= $v['name'].',';
            }elseif($assData['answers_ana'][$v['id']] > 8 && $assData['answers_ana'][$v['id']] <=16){
                $nomal .= $v['name'].',';
            }else{
                $weak .= $v['name'].',';
            }
        }


        $section->addTextBreak(1);
        $fancyTableStyleName = 'Fancy Table';
        $fancyTableStyle = array('borderSize' => 1, 'borderColor' => '006699', 'cellMargin' => 80, 'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER, 'cellSpacing' => 0);
        $fancyTableFirstRowStyle = array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF');
        $fancyTableCellStyle = array('valign' => 'center');
        $fancyTableFontStyle = array('bold' => true);
        $this-> phpWord-> addTableStyle($fancyTableStyleName, $fancyTableStyle, $fancyTableFirstRowStyle);
        $table = $section->addTable($fancyTableStyleName);


        // for ($r = 1; $r <= 2; $r++) {
        //     $table->addRow();
        //     if($r == 1){
        //         foreach ($str1 as $v){
        //             $table->addCell(1050, $fancyTableCellStyle)->addText($v, $fancyTableFontStyle);
        //         }
        //     }
        //     if($r == 2){
        //         foreach ($str2 as $v){
        //             $table->addCell(1050)->addText($v);
        //         }
        //     }
        // }


        $section -> addText('职业倾向测评分析详解',['name'=>'仿宋','size'=>14,'bold' => true,'lineHeight'  => 2],self::FONT_STYLE_NAME, self::PARAGRAPH_STYLE_NAME);
        $table = $section->addTable($fancyTableStyleName);
        $table->addRow();
        $table->addCell(2050, $fancyTableCellStyle)->addText("类型",['name'=>'仿宋','size'=>14,'lineHeight'  => 2], $fancyTableFontStyle);
        $table->addCell(7400, $fancyTableCellStyle)->addText("详解",['name'=>'仿宋','size'=>14,'lineHeight'  => 2], $fancyTableFontStyle);

        $table->addRow();
        $table->addCell(2050)->addText("技术型（TF）",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);
        $table->addCell(7400)->addText("愿意展示自己的技能，并不断提升自己的技术，发挥更为专业的能力。希望通过施展自己的技能以获取别人认可，并乐于接受来自于专业领域的挑战。",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);

        $table->addRow();
        $table->addCell(2050)->addText("管理型（GM）",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);
        $table->addCell(7400)->addText("追求组织中的管理职位，喜欢发号施令，领导众人，因此能够整合其他人的工作，并对组织中某项工作的绩效承担责任。",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);

        $table->addRow();
        $table->addCell(2050)->addText("自主型（AU）",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);
        $table->addCell(7400)->addText("希望可以按照自己的方式工作和生活，总能提供足够的灵活性，无法忍受公司种种的约束，追求无拘无束。",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);

        $table->addRow();
        $table->addCell(2050)->addText("安全型（SE）",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);
        $table->addCell(7400)->addText("喜欢稳定的职位，更为强调财务安全和就业安全，关注五险一金、养老金以及税收。对组织忠心耿耿，可以长久地从事某一行业。",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);

        $table->addRow();
        $table->addCell(2050)->addText("创造型（EC）",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);
        $table->addCell(7400)->addText("冒险能力强，手腕强硬，希望向周围的人证明你有能力创建一家企业，并且能够全方位的学习，以此来实现自己的创业计划。",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);

        $table->addRow();
        $table->addCell(2050)->addText("服务型（SV）",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);
        $table->addCell(7400)->addText("追求职业的价值取向，希望可以做一些利于他人的事，例如教育、环保、公益、慈善等。富有爱心，安全感和同情心。",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);

        $table->addRow();
        $table->addCell(2050)->addText("挑战型（CH）",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);
        $table->addCell(7400)->addText("总是跃跃欲试，希望战胜强硬的对手和克服面临的困难。多层次的、复杂的情况对你来说是一剂强心针，厌倦简单及重复的工作。",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);

        $table->addRow();
        $table->addCell(2050)->addText("生活型（LS）",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);
        $table->addCell(7400)->addText("家庭的需求和你个人的休息对你来说非常重要，因此你希望职业有足够的弹性，能让你平衡并整合个人的、家庭的和职业的矛盾，并且让他们协调统一地共同发展。",['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);

        return $section;
    }

    /**
     * 组装MBTI测试测试文本（当前只适用于本类）
     */
    private function GenerateMbticsTxt( $section, $data )
    {
        $row = TestMbtiAnswer::get( $data-> id );
        $cates = mbtiCate::all();
        $cs = [];
        foreach ($cates as $k => $v){
            $cs[$v['cate']] = $v['desc'];
        }

        $answers_ana = unserialize($row->answers_ana);

        $ae = isset($answers_ana['e']) ? $answers_ana['e'] : 0;
        $ai = isset($answers_ana['i']) ? $answers_ana['i'] : 0;
        $an = isset($answers_ana['n']) ? $answers_ana['n'] : 0;
        $as = isset($answers_ana['s']) ? $answers_ana['s'] : 0;
        $at = isset($answers_ana['t']) ? $answers_ana['t'] : 0;
        $af = isset($answers_ana['f']) ? $answers_ana['f'] : 0;
        $aj = isset($answers_ana['j']) ? $answers_ana['j'] : 0;
        $ap = isset($answers_ana['p']) ? $answers_ana['p'] : 0;

        $e = [
            'count' => $ae,
            'percent'   => round($ae/($ae+$ai),2),
            'name'  => '外向'
        ];
        $i = [
            'count' => $ai,
            'percent'   => 1- $e['percent'],
            'name'  => '内向'
        ];
        $n = [
            'count' => $an,
            'percent'   => round($an/($an+$as),2),
            'name'  => '直觉'
        ];
        $s = [
            'count' => $as,
            'percent'   => 1-$n['percent'],
            'name'  => '感觉'
        ];
        $t = [
            'count' => $at,
            'percent'   => round($at/($at+$af),2),
            'name'  => '思考'
        ];
        $f = [
            'count' => $af,
            'percent'   => 1-$t['percent'],
            'name'  => '情感'
        ];
        $j = [
            'count' => $aj,
            'percent'   => round($aj/($aj+$ap),2),
            'name'  => '判断'
        ];
        $p = [
            'count' => $ap,
            'percent'   => 1 - $j['percent'],
            'name'  => '感知'
        ];

        $str = '';
        if($ai>=$ae){
            $str .= 'i';
        }else{
            $str .= 'e';
        }
        if($an>=$as){
            $str .= 'n';
        }else{
            $str .= 's';
        }

        if($af>=$at){
            $str .= 'f';
        }else{
            $str .= 't';
        }

        if($ap>=$aj){
            $str .= 'p';
        }else{
            $str .= 'j';
        }

        $retArr = [
            'e' => $e,
            'i' => $i,
            'n' => $n,
            's' => $s,
            'j' => $j,
            'p' => $p,
            'f' => $f,
            't' => $t
        ];
        if($row -> imgs){
            $img = unserialize($row -> imgs);
        }




        $languageEnGb = new \PhpOffice\PhpWord\Style\Language(\PhpOffice\PhpWord\Style\Language::ZH_CN);

        $this-> phpWord->getSettings()->setThemeFontLang($languageEnGb);


        $section = $this-> phpWord->addSection();
        $this-> phpWord->addParagraphStyle(self::PARAGRAPH_STYLE_NAME, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,'spaceAfter' => 300,'spaceBefore' => 500));
        $section -> addText('MBTI 倾向示意图（你更倾向于：'.strtoupper($str).' 型）',$this -> titleStyle, self::PARAGRAPH_STYLE_NAME);



        if(isset($img)){
            $imgcount = count($img);
            foreach ($img as $ig){
                $imgpath = $_SERVER['DOCUMENT_ROOT'].$ig;
                if(!is_file($imgpath)) continue;
                $info = getimagesize($imgpath);
                $oheight = $height = $info[1];
                $owidth = $width = $info[0];
                if($imgcount == 1){
                    $width = min($width,430);
                    $height = intval($oheight * ($width/$owidth));
                }
                $section->addImage($_SERVER['DOCUMENT_ROOT'].$ig, array('width'=>$width, 'height'=>350));
            }
        }

        // $section -> addText('MBTI 测评得分占比',['name'=>'黑体','size'=>14,'bold' => true,'lineHeight'  => 2],self::FONT_STYLE_NAME, self::PARAGRAPH_STYLE_NAME);


        $tr1 = [];
        $tr2 = [];
        $tr3 = [];


        $arr = ['e','i','s','n','t','f','j','p'];
        foreach($arr as $vv){
            foreach($retArr as $k => $v){
                if($k == $vv){
                    $tr1[] = $v['name'].' '.strtoupper($k);
                    $tr2[] = $v['count'];
                    $tr3[] = ($v['percent']*100).'%';
                }
            }
        }


        $section->addTextBreak(1);
        $fancyTableStyleName = 'Fancy Table';
        $fancyTableStyle = array('borderSize' => 1, 'borderColor' => '006699', 'cellMargin' => 80, 'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER, 'cellSpacing' => 0);
        $fancyTableFirstRowStyle = array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF');
        $fancyTableCellStyle = array('valign' => 'center');
        $fancyTableFontStyle = array('bold' => true);
        $this-> phpWord->addTableStyle($fancyTableStyleName, $fancyTableStyle, $fancyTableFirstRowStyle);
        $table = $section->addTable($fancyTableStyleName);


        // for ($r = 1; $r <= 3; $r++) {
        //     $table->addRow();
        //     if($r == 1){
        //         foreach ($tr1 as $v){
        //             $table->addCell(1050, $fancyTableCellStyle)->addText($v, $fancyTableFontStyle);
        //         }
        //     }
        //     if($r == 2){
        //         foreach ($tr2 as $v){
        //             $table->addCell(1050)->addText($v);
        //         }
        //     }
        //     if($r == 3){
        //         foreach ($tr3 as $v){
        //             $table->addCell(1050)->addText($v);
        //         }
        //     }
        // }

        $section -> addText('MBTI 测评结果分析',['name'=>'黑体','size'=>14,'bold' => true,'lineHeight'  => 2],self::FONT_STYLE_NAME, self::PARAGRAPH_STYLE_NAME);
        $html = str_replace(array("<br>","'","<o:p>","</o:p>","&quot;",'calibri=""','light";=""','font-size:=""','16pt;"=""'),'',$cs[$str]);
        // $html = str_replace('你的类型是：','你的类型是：'.strtoupper($str),$html);
        // $html = '你的类型是：'.strtoupper($str);
        $section -> addText('综合你在四个维度上的倾向，总体来说，你的类型是：'.strtoupper($str).'型',[ 'size' => 16,'name' => '黑体' ]);//添加用户信息
        $section->  addPageBreak();                                                 //设置分页符
        \PhpOffice\PhpWord\Shared\Html::addHtml($section, false, false,['lineHeight'  => 2]);
        return $section;

    }


    /**
     * 组装MBTI测试测试文本（当前只适用于本类）
     */
    private function GenerateMbticsReport( $section, $data )
    {
        $row = TestMbtiAnswer::get( $data-> id );
        $cates = mbtiCate::all();
        $cs = [];
        // $as = [];
        foreach ($cates as $k => $v){
            // $cs[] = $v;
            $cs[$v['cate']] = $v['report'];
        }

        // pr($cs['esfp']);exit();
        $answers_ana = unserialize($row->answers_ana);

        $ae = isset($answers_ana['e']) ? $answers_ana['e'] : 0;
        $ai = isset($answers_ana['i']) ? $answers_ana['i'] : 0;
        $an = isset($answers_ana['n']) ? $answers_ana['n'] : 0;
        $as = isset($answers_ana['s']) ? $answers_ana['s'] : 0;
        $at = isset($answers_ana['t']) ? $answers_ana['t'] : 0;
        $af = isset($answers_ana['f']) ? $answers_ana['f'] : 0;
        $aj = isset($answers_ana['j']) ? $answers_ana['j'] : 0;
        $ap = isset($answers_ana['p']) ? $answers_ana['p'] : 0;

        $e = [
            'count' => $ae,
            'percent'   => round($ae/($ae+$ai),2),
            'name'  => '外向'
        ];
        $i = [
            'count' => $ai,
            'percent'   => 1- $e['percent'],
            'name'  => '内向'
        ];
        $n = [
            'count' => $an,
            'percent'   => round($an/($an+$as),2),
            'name'  => '直觉'
        ];
        $s = [
            'count' => $as,
            'percent'   => 1-$n['percent'],
            'name'  => '感觉'
        ];
        $t = [
            'count' => $at,
            'percent'   => round($at/($at+$af),2),
            'name'  => '思考'
        ];
        $f = [
            'count' => $af,
            'percent'   => 1-$t['percent'],
            'name'  => '情感'
        ];
        $j = [
            'count' => $aj,
            'percent'   => round($aj/($aj+$ap),2),
            'name'  => '判断'
        ];
        $p = [
            'count' => $ap,
            'percent'   => 1 - $j['percent'],
            'name'  => '感知'
        ];

        $str = '';
        if($ai>=$ae){
            $str .= 'i';
        }else{
            $str .= 'e';
        }
        if($an>=$as){
            $str .= 'n';
        }else{
            $str .= 's';
        }

        if($af>=$at){
            $str .= 'f';
        }else{
            $str .= 't';
        }

        if($ap>=$aj){
            $str .= 'p';
        }else{
            $str .= 'j';
        }

        $retArr = [
            'e' => $e,
            'i' => $i,
            'n' => $n,
            's' => $s,
            'j' => $j,
            'p' => $p,
            'f' => $f,
            't' => $t
        ];
        if($row -> imgs){
            $img = unserialize($row -> imgs);
        }

        $languageEnGb = new \PhpOffice\PhpWord\Style\Language(\PhpOffice\PhpWord\Style\Language::ZH_CN);

        $this-> phpWord->getSettings()->setThemeFontLang($languageEnGb);


        $section = $this-> phpWord->addSection();
        
        $section-> addText('报告总结',
            [
                'size'    => 18,
                'name'=>'黑体',
            ], [
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::LEFT,              //居中校准
                // 'spaceAfter'  => 300,                                                   //标题后部预留长度
                // 'spaceBefore' => 450,                                                    //标题前部预留长度
            ]
        );     //添加标题文本    
        $section->addText('__________________________________________________________________________________________',['name'=>'黑体'],['spaceAfter'  => 100,'spaceBefore' =>2,'alignment'=> \PhpOffice\PhpWord\SimpleType\Jc::CENTER]);

        $str = str_replace(array("<br>","'","<o:p>","</o:p>","&quot;",'calibri=""','light";=""','font-size:=""','16pt;"=""'),'',$cs[$str]);
        $html = '   根据您在各素质指标上的测评结果，按照您的能力、个性等特点来安排工作将能使你在工作中扬长避短，更好地完成工作任务，取得更高的工作绩效，为个人及公司带来更大的价值。在对认识自身的价值或面临工作安排时，您可以参考以下建议:      ';
        $section -> addText($html,['name'=>'仿宋','size'=>14]);//添加用户信息
        \PhpOffice\PhpWord\Shared\Html::addHtml($section,$str, false, false);
        return $section;

    }

    /**
     * 组装MBTI测试测试文本（当前只适用于本类）
     */
    private function GenerateMbticsAdvise( $section, $data )
    {
        $row = TestMbtiAnswer::get( $data-> id );
        $cates = mbtiCate::all();
        $cs = [];
        // $as = [];
        foreach ($cates as $k => $v){
            // $cs[] = $v;
            $cs[$v['cate']] = $v['advise'];
        }

        // pr($cs['esfp']);exit();
        $answers_ana = unserialize($row->answers_ana);

        $ae = isset($answers_ana['e']) ? $answers_ana['e'] : 0;
        $ai = isset($answers_ana['i']) ? $answers_ana['i'] : 0;
        $an = isset($answers_ana['n']) ? $answers_ana['n'] : 0;
        $as = isset($answers_ana['s']) ? $answers_ana['s'] : 0;
        $at = isset($answers_ana['t']) ? $answers_ana['t'] : 0;
        $af = isset($answers_ana['f']) ? $answers_ana['f'] : 0;
        $aj = isset($answers_ana['j']) ? $answers_ana['j'] : 0;
        $ap = isset($answers_ana['p']) ? $answers_ana['p'] : 0;

        $e = [
            'count' => $ae,
            'percent'   => round($ae/($ae+$ai),2),
            'name'  => '外向'
        ];
        $i = [
            'count' => $ai,
            'percent'   => 1- $e['percent'],
            'name'  => '内向'
        ];
        $n = [
            'count' => $an,
            'percent'   => round($an/($an+$as),2),
            'name'  => '直觉'
        ];
        $s = [
            'count' => $as,
            'percent'   => 1-$n['percent'],
            'name'  => '感觉'
        ];
        $t = [
            'count' => $at,
            'percent'   => round($at/($at+$af),2),
            'name'  => '思考'
        ];
        $f = [
            'count' => $af,
            'percent'   => 1-$t['percent'],
            'name'  => '情感'
        ];
        $j = [
            'count' => $aj,
            'percent'   => round($aj/($aj+$ap),2),
            'name'  => '判断'
        ];
        $p = [
            'count' => $ap,
            'percent'   => 1 - $j['percent'],
            'name'  => '感知'
        ];

        $str = '';
        if($ai>=$ae){
            $str .= 'i';
        }else{
            $str .= 'e';
        }
        if($an>=$as){
            $str .= 'n';
        }else{
            $str .= 's';
        }

        if($af>=$at){
            $str .= 'f';
        }else{
            $str .= 't';
        }

        if($ap>=$aj){
            $str .= 'p';
        }else{
            $str .= 'j';
        }

        $retArr = [
            'e' => $e,
            'i' => $i,
            'n' => $n,
            's' => $s,
            'j' => $j,
            'p' => $p,
            'f' => $f,
            't' => $t
        ];
        if($row -> imgs){
            $img = unserialize($row -> imgs);
        }

        $languageEnGb = new \PhpOffice\PhpWord\Style\Language(\PhpOffice\PhpWord\Style\Language::ZH_CN);

        $this-> phpWord->getSettings()->setThemeFontLang($languageEnGb);


        $section = $this-> phpWord->addSection();
    
        $section-> addText('人才发展建议',
            [
                'size'    => 18,
                'name'=>'黑体',
            ], [
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::LEFT,              //居中校准
                // 'spaceAfter'  => 300,                                                   //标题后部预留长度
                // 'spaceBefore' => 450,                                                    //标题前部预留长度
            ]
        );     //添加标题文本
        $section->addText('__________________________________________________________________________________________',['name'=>'黑体'],['spaceAfter'  => 1,'spaceBefore' =>2,'alignment'=> \PhpOffice\PhpWord\SimpleType\Jc::CENTER]);

        $str = str_replace(array("<br>","'","<o:p>","</o:p>","&quot;",'calibri=""','light";=""','font-size:=""','16pt;"=""'),'',$cs[$str]);
        // $html = '   ';
        // $section -> addText($html,['name'=>'仿宋','size'=>14,'lineHeight'  => 2]);//添加用户信息
        \PhpOffice\PhpWord\Shared\Html::addHtml($section,$str, false, false);
        return $section;

    }


    /**
     * 组装霍兰德测试文本（当前只适用于本类）
     */
    private function GenerateHldcsTxt( $section, $data )
    {
        $row = TestHldAnswer::get( $data-> id );

        if(!$row)
            $this -> redirect('hldtest');
        $answers_ana = unserialize($row->answers_ana);
        arsort($answers_ana);
        $r = array_slice($answers_ana,0,3);
        $str = '';
        foreach ($r as $k => $v){
            $str .= $k;
        }

        $cates = hldCate::all();
        $cs = [];
        foreach ($cates as $k => $v){
            $cs[$v['cate']] = $v['desc'];
        }
        $arr = ['r','c','e','s','a','i'];

        $a = unserialize($row -> answers_ana);
        $ana = [];
        foreach ($arr as $v){
            if(isset($a[$v]))
                $ana[$v] = $a[$v];
        }

        $languageEnGb = new \PhpOffice\PhpWord\Style\Language(\PhpOffice\PhpWord\Style\Language::ZH_CN);
        
        $this-> phpWord->getSettings()->setThemeFontLang($languageEnGb);


        $section = $this-> phpWord->addSection();
        $section-> addText('整体测评情况',
            [
                'size'    => 18,
                'name'=>'黑体',
            ], [
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::LEFT,              //居中校准
                // 'spaceAfter'  => 300,                                                   //标题后部预留长度
                // 'spaceBefore' => 450,                                                    //标题前部预留长度
            ]
        );     //添加标题文本  
        $section->addText('__________________________________________________________________________________________',['name'=>'黑体'],['spaceAfter'  => 300,'spaceBefore' =>2,'alignment'=> \PhpOffice\PhpWord\SimpleType\Jc::CENTER]);

        $this-> phpWord->addParagraphStyle(self::PARAGRAPH_STYLE_NAME, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,'spaceAfter' => 300,'spaceBefore' => 500));
        $section -> addText('霍兰德职业兴趣测评(您的测试结果倾向于 '.strtoupper($str).')',$this -> titleStyle, self::PARAGRAPH_STYLE_NAME);

        if( !empty( $row -> imgs ) )
        {
            $img = unserialize($row -> imgs);

            if(isset($img)){
                $imgcount = count($img);
                foreach ($img as $ig){
                    $imgpath = $_SERVER['DOCUMENT_ROOT'].$ig;
                    if(!is_file($imgpath)) continue;
                    $info = getimagesize($imgpath);
                    $oheight = $height = $info[1];
                    $owidth = $width = $info[0];
                    if($imgcount == 1){
                        $width = min($width,430);
                        // 图片高度太高了，调整图片高度
                        // $height = intval($oheight * ($width/$owidth));
                        $height = 400;
                    }
                    $section->addImage($_SERVER['DOCUMENT_ROOT'].$ig, array('width'=>$width, 'height'=>$height,'alignment'=> \PhpOffice\PhpWord\SimpleType\Jc::CENTER));
                }
            }

        }

        $section -> addText('霍兰德职业兴趣测评 '.strtoupper($str),['name'=>'仿宋','size'=>14,'lineHeight'  => 2],['alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER],self::FONT_STYLE_NAME, self::PARAGRAPH_STYLE_NAME);

        $html = str_replace(array("<br>","'","<o:p>","</o:p>","&quot;",'calibri=""','light";=""','font-size:=""','16pt;"=""'),'',$cs[$str]);
        \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false);
        return $section;
    }

    /**
     * 输出文件流
     * 传参：data：已设置好的phpWord模型
     */
    public function download( $data, $mobilePhone, $fileName ,$nickName)
    {
        if( empty( $data ) || empty( $fileName ) || empty( $mobilePhone ) )
            return false;
        if(ob_get_length()) ob_end_clean();//这一句必须，没有这一句，linux生成的word会提示文件损坏
        ob_start();
        // $fileName = 'uploads/20220624/18833034677-1920.docx';
//        echo $fileName;
        $objFile = \PhpOffice\PhpWord\IOFactory::createWriter( $this-> phpWord, 'Word2007');
        // echo 'ddddddddddd';
//        exit;
        $objFile->save( $fileName );
        // exit();

        $file = fopen ( $fileName, "rb" );
        // halt('333333');
        
        //告诉浏览器这是一个文件流格式的文件
        Header ( "Content-type: application/octet-stream" );
        //请求范围的度量单位
        Header ( "Accept-Ranges: bytes" );
        //Content-Length是指定包含于请求或响应中数据的字节长度
        Header ( "Accept-Length: " . filesize ( $fileName ) );
        //用来告诉浏览器，文件是可以当做附件被下载，下载后的文件名称为$file_name该变量的值。
        Header ( "Content-Disposition: attachment; filename=" . $nickName.$mobilePhone.'-'.(rand(1111,9999)).'.docx' );

        //读取文件内容并直接输出到浏览器
        echo fread ( $file, filesize ( $fileName ) );
        fclose ( $file );
        exit ();



        // // $filename = $district['name'].'-'.time();
        // // $filename = iconv('utf-8', 'gb2312', $filename);
        // header('pragma:public');
        // header('Content-type:application/vnd.ms-word;charset=utf-8;name="'.$fileName.'".doc');
        
        // Header ( "Content-Disposition: attachment; filename=" . $nickName.$mobilePhone.'-'.(rand(1111,9999)).'.docx' );
        // //attachment新窗口打印inline本窗口打印
        
        // $html = '<html xmlns:o="urn:schemas-microsoft-com:office:office"
        // xmlns:w="urn:schemas-microsoft-com:office:word"
        // xmlns="http://www.w3.org/TR/REC-html40"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>';//这句不能少，否则不能识别图片
        // echo $html.$data.'</html>';
        // exit();
    }

//    public function test()
//    {
//        $img1 = $_SERVER['DOCUMENT_ROOT'].'/assets/img/sida_logo.png';;
//        $img2 = $_SERVER['DOCUMENT_ROOT'].'/assets/img/sida_word_background.png';
//        $logo = imagecreatefrompng( $img1 );
//        $back = imagecreatefrompng( $img2 );
//        imagecopyresampled( $back, $logo,0,0,0,0,400,200,330,125 );
//        var_dump(imagejpeg($back,$_SERVER['DOCUMENT_ROOT']."./".'111111.png'));
//    }
}